/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.IllegalOrphanException;
import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.SystemAction;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.Actions;
import it.polimi.games.epkb.entityClasses.SystemActionOnComponent;
import java.util.ArrayList;
import java.util.Collection;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class SystemActionJpaController implements Serializable {

    public SystemActionJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }

    public SystemActionJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(SystemAction systemAction) throws IllegalOrphanException, PreexistingEntityException, Exception {
        if (systemAction.getSystemActionOnComponentCollection() == null) {
            systemAction.setSystemActionOnComponentCollection(new ArrayList<SystemActionOnComponent>());
        }
        List<String> illegalOrphanMessages = null;
        Actions actionsOrphanCheck = systemAction.getActions();
        if (actionsOrphanCheck != null) {
            SystemAction oldSystemActionOfActions = actionsOrphanCheck.getSystemAction();
            if (oldSystemActionOfActions != null) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("The Actions " + actionsOrphanCheck + " already has an item of type SystemAction whose actions column cannot be null. Please make another selection for the actions field.");
            }
        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Actions actions = systemAction.getActions();
            if (actions != null) {
                actions = em.getReference(actions.getClass(), actions.getId());
                systemAction.setActions(actions);
            }
            Collection<SystemActionOnComponent> attachedSystemActionOnComponentCollection = new ArrayList<SystemActionOnComponent>();
            for (SystemActionOnComponent systemActionOnComponentCollectionSystemActionOnComponentToAttach : systemAction.getSystemActionOnComponentCollection()) {
                systemActionOnComponentCollectionSystemActionOnComponentToAttach = em.getReference(systemActionOnComponentCollectionSystemActionOnComponentToAttach.getClass(), systemActionOnComponentCollectionSystemActionOnComponentToAttach.getSystemActionOnComponentPK());
                attachedSystemActionOnComponentCollection.add(systemActionOnComponentCollectionSystemActionOnComponentToAttach);
            }
            systemAction.setSystemActionOnComponentCollection(attachedSystemActionOnComponentCollection);
            em.persist(systemAction);
            if (actions != null) {
                actions.setSystemAction(systemAction);
                actions = em.merge(actions);
            }
            for (SystemActionOnComponent systemActionOnComponentCollectionSystemActionOnComponent : systemAction.getSystemActionOnComponentCollection()) {
                SystemAction oldSystemActionOfSystemActionOnComponentCollectionSystemActionOnComponent = systemActionOnComponentCollectionSystemActionOnComponent.getSystemAction();
                systemActionOnComponentCollectionSystemActionOnComponent.setSystemAction(systemAction);
                systemActionOnComponentCollectionSystemActionOnComponent = em.merge(systemActionOnComponentCollectionSystemActionOnComponent);
                if (oldSystemActionOfSystemActionOnComponentCollectionSystemActionOnComponent != null) {
                    oldSystemActionOfSystemActionOnComponentCollectionSystemActionOnComponent.getSystemActionOnComponentCollection().remove(systemActionOnComponentCollectionSystemActionOnComponent);
                    oldSystemActionOfSystemActionOnComponentCollectionSystemActionOnComponent = em.merge(oldSystemActionOfSystemActionOnComponentCollectionSystemActionOnComponent);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findSystemAction(systemAction.getId()) != null) {
                throw new PreexistingEntityException("SystemAction " + systemAction + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(SystemAction systemAction) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            SystemAction persistentSystemAction = em.find(SystemAction.class, systemAction.getId());
            Actions actionsOld = persistentSystemAction.getActions();
            Actions actionsNew = systemAction.getActions();
            Collection<SystemActionOnComponent> systemActionOnComponentCollectionOld = persistentSystemAction.getSystemActionOnComponentCollection();
            Collection<SystemActionOnComponent> systemActionOnComponentCollectionNew = systemAction.getSystemActionOnComponentCollection();
            List<String> illegalOrphanMessages = null;
            if (actionsNew != null && !actionsNew.equals(actionsOld)) {
                SystemAction oldSystemActionOfActions = actionsNew.getSystemAction();
                if (oldSystemActionOfActions != null) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("The Actions " + actionsNew + " already has an item of type SystemAction whose actions column cannot be null. Please make another selection for the actions field.");
                }
            }
            for (SystemActionOnComponent systemActionOnComponentCollectionOldSystemActionOnComponent : systemActionOnComponentCollectionOld) {
                if (!systemActionOnComponentCollectionNew.contains(systemActionOnComponentCollectionOldSystemActionOnComponent)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain SystemActionOnComponent " + systemActionOnComponentCollectionOldSystemActionOnComponent + " since its systemAction field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (actionsNew != null) {
                actionsNew = em.getReference(actionsNew.getClass(), actionsNew.getId());
                systemAction.setActions(actionsNew);
            }
            Collection<SystemActionOnComponent> attachedSystemActionOnComponentCollectionNew = new ArrayList<SystemActionOnComponent>();
            for (SystemActionOnComponent systemActionOnComponentCollectionNewSystemActionOnComponentToAttach : systemActionOnComponentCollectionNew) {
                systemActionOnComponentCollectionNewSystemActionOnComponentToAttach = em.getReference(systemActionOnComponentCollectionNewSystemActionOnComponentToAttach.getClass(), systemActionOnComponentCollectionNewSystemActionOnComponentToAttach.getSystemActionOnComponentPK());
                attachedSystemActionOnComponentCollectionNew.add(systemActionOnComponentCollectionNewSystemActionOnComponentToAttach);
            }
            systemActionOnComponentCollectionNew = attachedSystemActionOnComponentCollectionNew;
            systemAction.setSystemActionOnComponentCollection(systemActionOnComponentCollectionNew);
            systemAction = em.merge(systemAction);
            if (actionsOld != null && !actionsOld.equals(actionsNew)) {
                actionsOld.setSystemAction(null);
                actionsOld = em.merge(actionsOld);
            }
            if (actionsNew != null && !actionsNew.equals(actionsOld)) {
                actionsNew.setSystemAction(systemAction);
                actionsNew = em.merge(actionsNew);
            }
            for (SystemActionOnComponent systemActionOnComponentCollectionNewSystemActionOnComponent : systemActionOnComponentCollectionNew) {
                if (!systemActionOnComponentCollectionOld.contains(systemActionOnComponentCollectionNewSystemActionOnComponent)) {
                    SystemAction oldSystemActionOfSystemActionOnComponentCollectionNewSystemActionOnComponent = systemActionOnComponentCollectionNewSystemActionOnComponent.getSystemAction();
                    systemActionOnComponentCollectionNewSystemActionOnComponent.setSystemAction(systemAction);
                    systemActionOnComponentCollectionNewSystemActionOnComponent = em.merge(systemActionOnComponentCollectionNewSystemActionOnComponent);
                    if (oldSystemActionOfSystemActionOnComponentCollectionNewSystemActionOnComponent != null && !oldSystemActionOfSystemActionOnComponentCollectionNewSystemActionOnComponent.equals(systemAction)) {
                        oldSystemActionOfSystemActionOnComponentCollectionNewSystemActionOnComponent.getSystemActionOnComponentCollection().remove(systemActionOnComponentCollectionNewSystemActionOnComponent);
                        oldSystemActionOfSystemActionOnComponentCollectionNewSystemActionOnComponent = em.merge(oldSystemActionOfSystemActionOnComponentCollectionNewSystemActionOnComponent);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = systemAction.getId();
                if (findSystemAction(id) == null) {
                    throw new NonexistentEntityException("The systemAction with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            SystemAction systemAction;
            try {
                systemAction = em.getReference(SystemAction.class, id);
                systemAction.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The systemAction with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<SystemActionOnComponent> systemActionOnComponentCollectionOrphanCheck = systemAction.getSystemActionOnComponentCollection();
            for (SystemActionOnComponent systemActionOnComponentCollectionOrphanCheckSystemActionOnComponent : systemActionOnComponentCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This SystemAction (" + systemAction + ") cannot be destroyed since the SystemActionOnComponent " + systemActionOnComponentCollectionOrphanCheckSystemActionOnComponent + " in its systemActionOnComponentCollection field has a non-nullable systemAction field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Actions actions = systemAction.getActions();
            if (actions != null) {
                actions.setSystemAction(null);
                actions = em.merge(actions);
            }
            em.remove(systemAction);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<SystemAction> findSystemActionEntities() {
        return findSystemActionEntities(true, -1, -1);
    }

    public List<SystemAction> findSystemActionEntities(int maxResults, int firstResult) {
        return findSystemActionEntities(false, maxResults, firstResult);
    }

    private List<SystemAction> findSystemActionEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(SystemAction.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public SystemAction findSystemAction(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(SystemAction.class, id);
        } finally {
            em.close();
        }
    }

    public int getSystemActionCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<SystemAction> rt = cq.from(SystemAction.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
